import { defineComponent, h, onUnmounted, type PropType, ref } from 'vue';
import '../camera/style/index.css';
import { Button, Upload } from 'ant-design-vue';
// export type MouseEventHandler = (e: MouseEvent) => void;
export const ACamera = defineComponent({
  emits: ['refreshDataList'],
  name: 'ACamera',
  components: {
    'a-button': Button,
    'a-upload': Upload,
  },
  inheritAttrs: true,
  props: {
    width: { type: Number, required: true, default: 300 },
    height: { type: Number, required: true, default: 300 },
    accept: { type: String },
    action: { type: String, default: '' },
    disabled: { type: Boolean, default: false },
    headers: { type: Object },
    customRequest: { type: Function },
    fileList: { type: Array as PropType<Array<any>>, default: () => [] },
    onClick: { type: Function },
  },
  setup(props) {
    let canvas: any = null;
    let canvasContext: any = null;
    let videoCamera: any = null;
    const uploading = ref<boolean>(false);
    //打开摄像头
    const getCompetence = () => {
      console.log('take photo.');
      canvas = document.getElementById('canvasCamera');
      canvasContext = canvas.getContext('2d');
      videoCamera = document.getElementById('videoCamera');
      if (navigator.mediaDevices === undefined) {
        console.error(
          'getUserMedia is not implemented in this browser. Please check the "unsafely-treat-insecure-origin-as-secure" option on Chrome/Edge'
        );
        return;
      }
      const constraints = {
        audio: false,
        video: {
          width: props.width,
          height: props.height,
          transform: 'scaleX(-1)',
        },
      };
      window.navigator.mediaDevices
        .getUserMedia(constraints)
        .then((stream) => {
          videoCamera = document.getElementById('videoCamera');
          if (videoCamera != null) {
            if ('srcObject' in videoCamera) {
              videoCamera.srcObject = stream;
            }
          }
          videoCamera.onloadedmetadata = function () {
            videoCamera.play();
          };
        })
        .catch((error) => {
          console.error('Error accessing camera', error);
        });
    };
    const takePhoto = () => {
      // const emit = defineEmits(['refreshDataList']);
      console.log('take photo');
      if (navigator.mediaDevices === undefined) {
        console.error(
          'getUserMedia is not implemented in this browser. Please check the "unsafely-treat-insecure-origin-as-secure" option on Chrome/Edge'
        );
        return;
      }
      canvasContext.drawImage(canvas, 0, 0, props.width, props.height);
      const image = canvas.toDataURL('image/png');
      const file = image;
      const time = new Date().valueOf();
      const name = time + '.png';
      const conversions = base64ToFile(file, name);
      const formData = new FormData();
      formData.append('file', conversions);
      // chrome
      const link = document.createElement('a');
      link.href = window.URL.createObjectURL(conversions);
      link.download = 'screenshot.jpg';
      link.click();
      window.URL.revokeObjectURL(link.href);
      // const url = props.action;
      // fetch(url, {
      //   method: 'post',
      //   headers: {
      //     token: '2wq7mRGAzA24DdMxdqLzoVeOexRkyPqC',
      //   },
      //   body: formData,
      // })
      //   .then((response) => response.json())
      //   .then((data) => {
      //     if (data) {
      //       ctx.emit('refreshDataList', data[0]);
      //     }
      //   });
    };
    // base64图片转file的方法（base64图片, 设置生成file的文件名）
    const base64ToFile = (base64: string, fileName: string) => {
      // 将base64按照 , 进行分割 将前缀  与后续内容分隔开
      const data = base64.split(',');
      // 利用正则表达式 从前缀中获取图片的类型信息（image/png、image/jpeg、image/webp等）
      const type = data[0].match(/:(.*?);/)![1];
      // 从图片的类型信息中 获取具体的文件格式后缀（png、jpeg、webp）
      const suffix = type.split('/')[1];
      // 使用atob()对base64数据进行解码  结果是一个文件数据流 以字符串的格式输出
      const bstr = window.atob(data[1]);
      // 获取解码结果字符串的长度
      let n = bstr.length;
      // 根据解码结果字符串的长度创建一个等长的整形数字数组
      // 但在创建时 所有元素初始值都为 0
      const u8arr = new Uint8Array(n);
      // 将整形数组的每个元素填充为解码结果字符串对应位置字符的UTF-16 编码单元
      while (n--) {
        // charCodeAt()：获取给定索引处字符对应的 UTF-16 代码单元
        u8arr[n] = bstr.charCodeAt(n);
      }
      // 利用构造函数创建File文件对象
      // new File(bits, name, options)
      const file = new File([u8arr], `${fileName}.${suffix}`, {
        type: type,
      });
      // 将File文件对象返回给方法的调用者
      return file;
    };
    const stopNavigator = () => {
      videoCamera.srcObject.getTracks()[0].stop();
    };
    onUnmounted(() => {
      videoCamera.srcObject.getTracks()[0].stop();
    });

    return {
      uploading,
      takePhoto,
      getCompetence,
      stopNavigator,
    };
  },

  render() {
    return h(
      'div',
      {
        class: 'camera_outer',
        style: {
          width: this.$props.width + 'px',
        },
      },
      [
        h('video', {
          id: 'videoCamera',
          width: this.$props.width,
          height: this.$props.height,
          props: { autoplay: true },
        }),
        h('canvas', {
          id: 'canvasCamera',
          style: 'display: none',
          width: this.$props.width,
          height: this.$props.height,
        }),
        h(
          'div',
          {
            style: {
              display: 'flex',
              justifyContent: 'space-between',
              alignItems: 'center',
              margin: '0px 10px 10px 10px',
            },
          },
          [
            h(
              Button,
              {
                onClick: this.getCompetence,
              },
              '打开摄像头'
            ),
            // h(
            //   Upload,
            //   {
            //     name: '',
            //     action: this.$props.action?.toString(),
            //     // fileList: this.$props.fileList,
            //     fileList: this.$props.fileList,
            //     openFileDialogOnClick: false,
            //     onChange: this.stopNavigator,
            //   },
            //   [
            //     h(
            //       Button,
            //       {
            //         style: {
            //           display: 'none',
            //         },
            //       },
            //       '___拍照上传___'
            //     ),
            //   ]
            // ),
            h(
              Button,
              {
                uploading: this.uploading,
                onClick: this.takePhoto,
              },
              '拍照'
            ),
          ]
        ),
      ]
    );
  },
});
